﻿using System;
using System.Linq;
using Orchard;
using Orchard.Events;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.UI.Notify;
using Hazdesign.TwitterRules.Services;

namespace Hazdesign.TwitterRules.Rules{
    public interface IActionProvider : IEventHandler{
        void Describe(dynamic describe);
    }

    public class PublishingActions {
        private readonly IPublishingService _publishingService;
        private readonly IOrchardServices _orchardServices;
        protected PublishingActions(
            IPublishingService publishingService,
            IOrchardServices orchardServices)
        {
            this._publishingService = publishingService;
            this._orchardServices = orchardServices;
            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }
        public ILogger Logger { get; set; }

        protected bool Publish(dynamic context){
            var content = context.Properties["Tweet"];

            var user = this._orchardServices.WorkContext.CurrentUser;
            // can be null if user is anonymous
            if (user == null){
                this._orchardServices.Notifier.Add(NotifyType.Warning, T("The message '{0}' was not published, only authenticated users can publish messages.", content.ToString()));
                return true;
            }

            var message = this._publishingService.GetMessage(user, content);

            try{
                var success = this._publishingService.Publish(message);
                if (success) {
                    this._orchardServices.Notifier.Add(NotifyType.Information, T("The message '{0}' was published succesfuly.", message.PublishMessage));
                }
            } catch(Exception exception) {
                var errorMessage = T("There was an error while trying to publish the message: '{0}'. {1}", message.PublishMessage, exception.ToString());
                this._orchardServices.Notifier.Add(NotifyType.Error, errorMessage);
                Logger.Log(LogLevel.Error, exception, errorMessage);
            }
            return true;
        }
    }
}